const co = require('co');
const express = require('express');
const logger = require('flogger').getLogger();
const config = require('config');
const Session = require('../util/session');
const auth = require('../util/auth');
const Utility = require('../util/util').Utility;
const roles = require('../constants/constant').roles;
const router = express.Router();
const TeamService = require('../services/team-service');
const User = require('../models').User;

const idType = {
  order: 'orderId',
  inquiry: 'inquiryId',
  product: 'productId',
  store: 'chatTo'
};

// 获取token
router.get('/auth', (req, res, next) => {
  co(function* () {
    let id = Session.getCurrentUserId(req) || req.current_user_id;
    let uid = yield Session.getCurrentUserUid(id, User);
    let token = yield auth.getToken(uid);
    res.end(token);
  }).catch(next);
});


/**
 * 渲染聊天页面
 */
router.get('/chat', function (req, res, next) {
  let id = Session.getCurrentUserId(req) || req.current_user_id;
  var chatTo = req.query.chatTo;
  var type = req.query.type || 'store';
  var clueId = req.query[idType[type]];

  let serviceN3DId = req.query.serviceId;
  let customerN3DId = req.query.customerId;
  logger.info(`客服Id：${serviceN3DId},用户Id：${customerN3DId}`);

  let serviceId = serviceN3DId ? Utility.stringToNumber(serviceN3DId) : '';
  let customerId = customerN3DId ? Utility.stringToNumber(customerN3DId) : '';
  logger.info(`客服Id：${serviceId},用户Id：${customerId}`);

  // 当前用户id与链接用户id身份不一致
  if (customerN3DId && id !== customerId) {
    res.send('<meta http-equiv="Refresh" content="3;url=/">' +
      '<p>无效的会话,3秒后将回到主页,点击<a href="/">立即返回</a></p>');
    return;
  }

  logger.info(`用户 ${id} 开始与 ${chatTo} 进行会话`);
  co(function* () {
    let username = yield Session.getCurrentUserUid(id, User);
    if (!username) {
      res.send('<meta http-equiv="Refresh" content="3;url=/">' +
        '<p>用户不存在,3秒后将回到主页,点击<a href="/">立即返回</a></p>');
      return;
    }

    logger.info(`用户 ${username} 开始与 ${chatTo} 进行会话`);

    var meta = {};
    meta.username = username;
    meta.chatId = chatTo;
    meta.type = type;
    meta.clueId = clueId;

    meta.target = {
      storeId: chatTo,
      storeName: '',
      services: []
    }

    // 指定的客服
    let specialService = serviceId ? yield User.findById(serviceId) : null;
    if (specialService) {
      if (specialService.storeId !== chatTo) {
        return res.send('<meta http-equiv="Refresh" content="3;url=/">' +
          '<p>无效的会话(店铺不一致),3秒后将回到主页,点击<a href="/">立即返回</a></p>');
      }
      specialService = specialService.get({plain: true});
      specialService.id = Utility.numberToString(specialService.id);
      logger.info(`指定店铺${specialService.storeId}(${specialService.storeName})的客服为：`, JSON.stringify(specialService, null, 2));
      meta.target.specialService = specialService;
      meta.target.storeName = specialService.storeName;
    } else {
      // 所有客服
      let teams = yield TeamService.queryTeamsDetail(chatTo, roles.CUSTOMER_SERVICE_ROLE);
      let allServices = [];
      teams.forEach(team => {
        allServices = allServices.concat(team.Users);
      });

      logger.info('查找到所有客服', JSON.stringify(allServices, null, 2));

      if (!allServices.length) {
        res.send('<meta http-equiv="Refresh" content="3;url=/">' +
          '<p>无效的会话,3秒后将回到主页,点击<a href="/">立即返回</a></p>');
        return;
      }

      meta.target = {
        storeId: allServices[0].storeId,
        storeName: allServices[0].storeName,
        services: allServices
      };
    }
    res.locals.title = '在线客服';
    res.locals.meta = meta;
    res.locals.appKey = config.RONGCLOUD_APP_KEY;
    res.render('chat-new');
  }).catch(function (error) {
    logger.warn('获取 %s 的用户信息失败', id, error.stack);
    next(error);
  });
});

module.exports = router;
